import asyncio
import json
import logging
import os
import sys
import time
from datetime import datetime
from PyQt5.QtCore import QObject, pyqtSignal, QTimer
from models.user import WeChatUser
import requests

logger = logging.getLogger(__name__)

class WeChatController(QObject):
    message_received = pyqtSignal(object)
    group_message_received = pyqtSignal(object)  # 新增群聊消息信号
    file_received = pyqtSignal(object)  # 新增文件消息信号

    def __init__(self):
        super().__init__()
        self.running = False
        self.users = []
        self.groups = []  # 群组列表
        self.whitelist_users = []
        self.message_history = []  # 消息历史记录
        self.group_message_history = []  # 群聊消息历史
        self.file_message_history = []  # 文件消息历史
        self.load_users()
        self.load_groups()  # 加载群组
        self.sync_whitelist_from_backend()

    def start_listening(self):
        logger.info("开始监听微信消息...")
        self.running = True
        try:
            while self.running:
                # 模拟收到私聊消息
                test_user = WeChatUser("张三", "user123", True)
                if test_user.is_whitelisted:
                    logger.info(f"收到白名单用户消息: {test_user.username}")
                    self.message_received.emit(test_user)
                    self.add_message_to_history(test_user, "这是一条测试消息")

                # 模拟收到群聊消息
                test_group = {
                    'groupId': 'group789',
                    'groupName': '测试群',
                    'content': '大家好！',
                    'sender': '王五'
                }
                logger.info(f"收到群聊消息: {test_group['groupName']}")
                self.group_message_received.emit(test_group)
                self.add_group_message_to_history(test_group)

                # 模拟收到文件消息
                self.simulate_file_received()

                time.sleep(5)
        except Exception as e:
            logger.error(f"监听异常: {e}")
            self.stop_listening())

    def stop_listening(self):
        logger.info("停止监听微信消息")
        self.running = False

    def load_users(self):
        # 加载本地用户列表（从数据库或 API 获取）
        # 这里模拟加载数据
        self.users = [
            WeChatUser("李四", "user456", False),
            WeChatUser("王五", "user789", True)
        ]
        logger.info(f"已加载 {len(self.users)} 个用户")

    def load_groups(self):
        # 加载本地群组列表（模拟）
        self.groups = [
            {'groupId': 'group456', 'groupName': 'VIP客户群'},
            {'groupId': 'group789', 'groupName': '测试群'}
        ]
        logger.info(f"已加载 {len(self.groups)} 个群组")

    def sync_whitelist_from_backend(self):
        """从后端 API 获取最新白名单用户"""
        try:
            res = requests.get("http://localhost:8080/api/users/whitelist")
            if res.status_code == 200:
                whitelist_data = res.json()
                self.whitelist_users = [WeChatUser.from_dict(u) for u in whitelist_data]
                logger.info(f"成功同步 {len(self.whitelist_users)} 个白名单用户")

                # 更新本地用户列表的白名单状态
                for user in self.users:
                    user.is_whitelisted = any(u.user_id == user.user_id for u in self.whitelist_users)

        except Exception as e:
            logger.error(f"同步白名单失败: {e}")

    def add_message_to_history(self, user, content):
        """添加消息到历史记录并同步到后端"""
        message = {
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'userId': user.user_id,
            'username': user.username,
            'content': content,
            'isWhitelisted': user.is_whitelisted
        }
        self.message_history.append(message)
        logger.info(f"消息已添加到历史记录: {message}")

        # 同步到后端
        try:
            res = requests.post("http://localhost:8080/api/messages/save", json=message)
            if res.status_code == 200:
                logger.info("消息已同步到后端")
            else:
                logger.warning(f"消息同步失败，状态码：{res.status_code}")
        except Exception as e:
            logger.error(f"同步消息到后端失败: {e}")

    def add_group_message_to_history(self, group_msg):
        """添加群聊消息到历史记录并同步到后端"""
        message = {
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'groupId': group_msg['groupId'],
            'groupName': group_msg['groupName'],
            'sender': group_msg['sender'],
            'content': group_msg['content'],
            'status': '已处理'
        }
        self.group_message_history.append(message)
        logger.info(f"群聊消息已添加到历史记录: {message}")

        # 同步到后端
        try:
            res = requests.post("http://localhost:8080/api/messages/save", json={
                'userId': '',
                'username': group_msg['sender'],
                'groupId': group_msg['groupId'],
                'groupName': group_msg['groupName'],
                'content': group_msg['content'],
                'isGroupMessage': True,
                'timestamp': message['timestamp']
            })
            if res.status_code == 200:
                logger.info("群聊消息已同步到后端")
            else:
                logger.warning(f"群聊消息同步失败，状态码：{res.status_code}")
        except Exception as e:
            logger.error(f"同步群聊消息到后端失败: {e}")

    def simulate_file_received(self):
        """模拟收到文件消息"""
        file_msg = {
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'userId': 'user456',
            'username': '李四',
            'fileName': '报告.pdf',
            'fileSize': '2.3MB',
            'status': '已接收'
        }
        logger.info(f"收到文件: {file_msg['fileName']}")
        self.file_received.emit(file_msg)
        self.add_file_to_history(file_msg)

    def add_file_to_history(self, file_msg):
        """添加文件消息到历史记录并同步到后端"""
        message = {
            'timestamp': file_msg['timestamp'],
            'userId': file_msg['userId'],
            'username': file_msg['username'],
            'fileName': file_msg['fileName'],
            'fileSize': file_msg['fileSize'],
            'status': file_msg['status']
        }
        self.file_message_history.append(message)
        logger.info(f"文件消息已添加到历史记录: {message}")

        # 同步到后端
        try:
            res = requests.post("http://localhost:8080/api/messages/save", json={
                'userId': file_msg['userId'],
                'username': file_msg['username'],
                'content': f"[文件] {file_msg['fileName']} ({file_msg['fileSize']})",
                'isFile': True,
                'timestamp': message['timestamp']
            })
            if res.status_code == 200:
                logger.info("文件消息已同步到后端")
            else:
                logger.warning("文件消息同步失败，状态码：", res.status_code)
        except Exception as e:
            logger.error(f"同步文件消息到后端失败: {e}")

    def get_message_history(self):
        """获取消息历史记录"""
        return self.message_history

    def send_message(self, user_id, message):
        logger.info(f"发送消息给用户 {user_id}: {message}")
        # 实际调用微信接口发送消息